<template>
  <div class='user-profile-page'>
    <van-nav-bar left-arrow @click-left="$router.back()" title="个人信息"></van-nav-bar>
    <van-cell-group>
      <van-cell is-link title="头像" center @click="showPhoto= true">
        <!-- 通过 v-model 控制弹出层是否展示 -->
       <van-action-sheet
         v-model="showPhoto"
         :actions="actions"
         @select="onPhotoSelect"
         cancel-text="取消"
         @cancel="onCancel"
       />
       <!-- 点击本地上传，调用file输入框 -->
       <input type="file" ref="file" accept="image/*" @change="updatePhoto" style="display:none">
       <!-- type 类型，表示是一个上传文件的input
            accept 上传的类型，代表是图片
            @change 在选中文件之后触发 -->
        <van-image
          slot="default"
          fit="cover"
          round
          :src="person.photo"
        />
      </van-cell>
      <!-- 修改昵称 -->
    <van-popup class="my-popup" v-model="showName" position="right">
      <van-nav-bar
        left-arrow
        @click-left="showName=false"
        @click-right="saveName()"
        right-text="保存"
        title="修改昵称"
      />
      <van-field v-model="name"></van-field>
    </van-popup>
      <van-cell is-link title="昵称" @click="openName()" :value=" person.name || '未填写'" />

    </van-cell-group>
    <van-cell-group style="margin-top:12px">
      <!-- 修改性别 -->
    <van-action-sheet
      v-model="showGender"
      :actions="[{ name: '男', value: 0 }, { name: '女', value: 1 }]"
      @select="saveGender"
      cancel-text="取消"
    />
    <van-cell is-link title="性别" @click="showGender=true" :value="person.gender===0?'男':'女'" />

     <!-- 修改生日 -->
     <!-- @cancel点击取消按钮时触发的事件 -->
    <van-popup v-model="showBirthday" position="bottom">
      <van-datetime-picker
        v-model="birthday"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="showBirthday=false"
        @confirm="saveBirthday"
      />
    </van-popup>
      <van-cell is-link title="生日" @click="openBirthday" :value="person.birthday|| '未填写'" />
    </van-cell-group>
    <div class="logout">
      <span @click="del">退出登录</span>
    </div>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import { Toast } from 'vant'
import { personal, updatePhoto, updateUser } from '@/api/user'
import { delToken } from '@/utils/storage'
export default {
  name: 'UserProfilePage',
  data () {
    return {
      // 修改头像
      person: {},
      showPhoto: false,
      actions: [{ name: '拍照', value: 0 }, { name: '本地上传', value: 1 }],
      // 修改用户名称
      showName: false,
      name: '',
      // 修改用户性别
      showGender: false,
      // 修改生日
      showBirthday: false,
      birthday: new Date(),
      minDate: new Date('1960-01-01'),
      maxDate: new Date()
    }
  },
  async created () {
    const res = await personal()
    console.log(res)
    this.person = res.data
  },
  methods: {
    del () {
      delToken()
      this.$router.push('/login')
    },
    onCancel () {
      Toast('取消')
    },
    // 选择修改头像-动作面板选项
    onPhotoSelect (item) {
      if (item.value === 1) {
        // 本地选择
        this.$refs.file.click()
        this.showPhoto = false
      }
    },
    // 修改头像
    async updatePhoto () {
      // console.log(e)//e.target.files[0]
      const file = this.$refs.file.files[0]
      // 手写的input需要一个对象将本地图片转换为对应的格式来上传
      // 1. 包装一个formData对象，字段名字photo指向的是选择的图片
      const formData = new FormData()

      // e.target.files就是上传的文件的一个数组
      formData.append('photo', file)
      // console.log(formData)

      // 将formData这个对象传给修改头像的接口
      const res = await updatePhoto(formData)
      // console.log(res)
      // 显示上传成功的头像,成功提示
      this.person.photo = res.data.photo
      this.$toast.success('修改成功')
    },
    // 修改昵称
    openName () {
      this.showName = true
      this.name = this.person.name
    },
    // 保存昵称
    async saveName () {
      if (!this.name) return this.$toast('请输入昵称')
      // 发请求
      await updateUser({ name: this.name })
      // console.log(res)
      // if (err) return this.$toast.fail('更新失败')
      // 更新单元格中的昵称
      this.person.name = this.name
      this.showName = false
      this.$toast.success('更新成功')
    },
    // 修改性别
    async saveGender (item) {
      const res = await updateUser({ gender: item.value })
      console.log(res)
      this.person.gender = item.value
      this.showGender = false
      this.$toast.success('更新成功')
    },
    // 打开日期选择器
    openBirthday () {
      this.showBirthday = true
      // 给日期控件赋值，当前用户的生日
      this.birthday = new Date(this.person.birthday)
    },
    // 修改用户生日
    async saveBirthday () {
      // 转换格式
      const date = dayjs(this.birthday).format('YYYY-MM-DD')
      const res = await updateUser({ birthday: date })
      console.log(res)
      // if (err) return this.$toast.fail('更新失败')
      this.person.birthday = date
      this.showBirthday = false
      this.$toast.success('更新成功')
    }
  }
}

</script>
<style lang="less" scoped>
.my-popup {
  width: 100%;
  height: 100%;
  /deep/ .van-nav-bar__text {
    color: #fc6627;
  }
  /deep/ .van-field__control {
    background: #f7f8fa;
    padding: 10px;
    border-radius: 4px;
  }
}
.user-profile-page {
  background: #f8f8f8;
  .van-image {
    display: block;
    float: right;
    width: 30px;
    height: 30px;
  }
  .van-cell__title {
    width: 50px;
    flex: none;
  }
}
.logout {
  text-align: center;
  position: absolute;
  left: 0;
  bottom: 30px;
  width: 100%;
  color: red;
}
.profile{
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  text-align: center;
  width: 100%;
  height: 100%;
}
</style>
